import {inject, provide, ref} from "vue";
import {User} from "../types/user";
import {Ref} from "@vue/reactivity";
import {request} from "../utils/request/client";
import {TableColumnDefine} from "../types/table-column";

const UserSymbol = Symbol()

export const useUserProvider = () => {
    const users = ref<User[]>()
    const setUsers = (value: Array<User>) => users.value = value

    provide(UserSymbol, {
        users,
        setUsers
    })
}

export const useUser = () => {
    const userContext: {users: Ref<User[]>, setUsers: (value: Array<User>) => void} | undefined = inject(UserSymbol)
    if (!userContext) {
        throw new Error('useUser Hook must be used after useUserProvider Hook')
    }

    const {users, setUsers} = userContext

    const loading = ref<boolean>(false)

    const listUsers = async (): Promise<User[]> => {
        loading.value = true
        const {data} = await request.get<User[]>('/api/user/list')
        setUsers(data)
        loading.value = false
        return data
    }

    const add = async (user: User): Promise<boolean> => {
        const {data} = await request.post<boolean>('/api/user/add', user)
        return data
    }

    const edit = async (user: User): Promise<boolean> => {
        const {data} = await  request.post<boolean>('/api/user/edit', user)
        return data
    }

    const remove = async (userId: number): Promise<boolean> => {
        const {data} = await request.get<boolean>(`/api/user/remove/${userId}`)
        return data
    }

    const getById = async (userId: number): Promise<User> => {
        const {data} = await request.get<User>(`/api/user/get/${userId}`)
        return data
    }

    const tableColumns: Array<TableColumnDefine> = [
        {name:'account',align:'center',label:'登录账号',field:'account'},
        {name:'name',align:'center',label:'用户名',field:'name'},
        {name:'action',align:'center',label:'操作',field:'action'}
    ]

    return {
        ...userContext,
        loading,
        listUsers,
        add,
        edit,
        remove,
        getById,
        tableColumns
    }
}